{% extends "base.html" %}

{% block title %}{{ page_title }} - 乒乓球培训管理系统{% endblock %}

{% block extra_css %}
<style>
    .transaction-detail-container {
        max-width: 800px;
        margin: 0 auto;
    }

    .transaction-header {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border-radius: 15px;
        padding: 2rem;
        margin-bottom: 2rem;
        text-align: center;
    }

    .transaction-icon {
        width: 80px;
        height: 80px;
        border-radius: 50%;
        background: rgba(255,255,255,0.2);
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 0 auto 1rem;
        font-size: 2rem;
    }

    .transaction-amount {
        font-size: 3rem;
        font-weight: bold;
        margin: 1rem 0;
    }

    .transaction-status {
        padding: 0.5rem 1.5rem;
        border-radius: 25px;
        font-weight: 500;
        display: inline-block;
    }

    .status-completed {
        background: rgba(40,167,69,0.2);
        color: #28a745;
        border: 1px solid rgba(40,167,69,0.3);
    }

    .status-pending {
        background: rgba(255,193,7,0.2);
        color: #ffc107;
        border: 1px solid rgba(255,193,7,0.3);
    }

    .status-failed {
        background: rgba(220,53,69,0.2);
        color: #dc3545;
        border: 1px solid rgba(220,53,69,0.3);
    }

    .detail-card {
        background: white;
        border-radius: 15px;
        padding: 2rem;
        margin-bottom: 2rem;
        box-shadow: 0 5px 20px rgba(0,0,0,0.1);
    }

    .detail-row {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 1rem 0;
        border-bottom: 1px solid #f0f0f0;
    }

    .detail-row:last-child {
        border-bottom: none;
    }

    .detail-label {
        font-weight: 500;
        color: #6c757d;
        display: flex;
        align-items: center;
        gap: 0.5rem;
    }

    .detail-value {
        font-weight: 500;
        color: #495057;
    }

    .detail-value.highlight {
        color: #007bff;
        font-weight: bold;
    }

    .detail-value.amount-positive {
        color: #28a745;
        font-weight: bold;
    }

    .detail-value.amount-negative {
        color: #dc3545;
        font-weight: bold;
    }

    .action-buttons {
        display: flex;
        gap: 1rem;
        margin-top: 2rem;
        flex-wrap: wrap;
    }

    .btn-action {
        flex: 1;
        min-width: 150px;
        padding: 0.75rem 1.5rem;
        border-radius: 25px;
        font-weight: 500;
        transition: all 0.3s ease;
    }

    .btn-action:hover {
        transform: translateY(-2px);
        box-shadow: 0 5px 15px rgba(0,0,0,0.2);
    }

    .refund-notice {
        background: #fff3cd;
        border: 1px solid #ffeaa7;
        border-radius: 10px;
        padding: 1rem;
        margin-bottom: 2rem;
    }

    .refund-notice .notice-title {
        color: #856404;
        font-weight: 600;
        margin-bottom: 0.5rem;
    }

    .refund-notice .notice-text {
        color: #856404;
        margin: 0;
        font-size: 0.9rem;
    }

    .timeline {
        position: relative;
        padding-left: 2rem;
    }

    .timeline::before {
        content: '';
        position: absolute;
        left: 8px;
        top: 0;
        bottom: 0;
        width: 2px;
        background: #dee2e6;
    }

    .timeline-item {
        position: relative;
        margin-bottom: 1.5rem;
    }

    .timeline-item::before {
        content: '';
        position: absolute;
        left: -5px;
        top: 5px;
        width: 10px;
        height: 10px;
        border-radius: 50%;
        background: #007bff;
        border: 2px solid white;
        box-shadow: 0 0 0 2px #007bff;
    }

    .timeline-content {
        background: #f8f9fa;
        border-radius: 8px;
        padding: 1rem;
        margin-left: 1rem;
    }

    .timeline-time {
        font-size: 0.8rem;
        color: #6c757d;
        margin-bottom: 0.5rem;
    }

    .qr-code-section {
        text-align: center;
        padding: 2rem;
        background: #f8f9fa;
        border-radius: 10px;
        margin: 2rem 0;
    }

    .qr-code {
        width: 200px;
        height: 200px;
        margin: 1rem auto;
        border: 1px solid #dee2e6;
        border-radius: 8px;
        background: white;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 4rem;
        color: #6c757d;
    }

    @media (max-width: 768px) {
        .transaction-amount {
            font-size: 2rem;
        }

        .detail-row {
            flex-direction: column;
            align-items: flex-start;
            gap: 0.5rem;
        }

        .action-buttons {
            flex-direction: column;
        }

        .btn-action {
            min-width: auto;
        }
    }
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <div class="transaction-detail-container">
        <!-- 页面标题 -->
        <div class="row mb-4">
            <div class="col-12">
                <nav aria-label="breadcrumb">
                    <ol class="breadcrumb justify-content-center">
                        <li class="breadcrumb-item"><a href="{{ url_for('dashboard.student') }}">首页</a></li>
                        <li class="breadcrumb-item"><a href="{{ url_for('accounts.balance') }}">账户余额</a></li>
                        <li class="breadcrumb-item"><a href="{{ url_for('accounts.transactions') }}">交易记录</a></li>
                        <li class="breadcrumb-item active">交易详情</li>
                    </ol>
                </nav>
            </div>
        </div>

        <!-- 交易概览 -->
        <div class="transaction-header">
            <div class="transaction-icon">
                {% if transaction.type == 'recharge' %}
                    <i class="fas fa-plus-circle"></i>
                {% elif transaction.type == 'reservation' %}
                    <i class="fas fa-calendar-check"></i>
                {% elif transaction.type == 'consume' %}
                    <i class="fas fa-minus-circle"></i>
                {% elif transaction.type == 'refund' %}
                    <i class="fas fa-undo"></i>
                {% elif transaction.type == 'penalty' %}
                    <i class="fas fa-exclamation-triangle"></i>
                {% elif transaction.type == 'freeze' %}
                    <i class="fas fa-lock"></i>
                {% elif transaction.type == 'unfreeze' %}
                    <i class="fas fa-unlock"></i>
                {% else %}
                    <i class="fas fa-exchange-alt"></i>
                {% endif %}
            </div>

            <h3>{{ transaction.description }}</h3>

            <div class="transaction-amount">
                {% if transaction.amount > 0 %}+{% endif %}¥{{ "%.2f"|format(transaction.amount) }}
            </div>

            <div class="transaction-status status-{{ transaction.status }}">
                {% if transaction.status == 'completed' %}
                    <i class="fas fa-check-circle me-2"></i>交易成功
                {% elif transaction.status == 'pending' %}
                    <i class="fas fa-clock me-2"></i>处理中
                {% elif transaction.status == 'failed' %}
                    <i class="fas fa-times-circle me-2"></i>交易失败
                {% else %}
                    {{ transaction.status }}
                {% endif %}
            </div>
        </div>

        <!-- 退款提示 -->
        {% if can_refund %}
        <div class="refund-notice">
            <div class="notice-title">
                <i class="fas fa-info-circle me-2"></i>退款说明
            </div>
            <p class="notice-text">
                此交易支持申请退款。如需退款，请在交易完成后30天内提交申请。
                退款将原路返回至您的支付账户，处理时间为1-3个工作日。
            </p>
        </div>
        {% endif %}

        <!-- 交易详情 -->
        <div class="detail-card">
            <h5 class="mb-4">
                <i class="fas fa-info-circle me-2"></i>交易详情
            </h5>

            <div class="detail-row">
                <div class="detail-label">
                    <i class="fas fa-hashtag"></i>交易编号
                </div>
                <div class="detail-value highlight">{{ transaction.id }}</div>
            </div>

            <div class="detail-row">
                <div class="detail-label">
                    <i class="fas fa-tag"></i>交易类型
                </div>
                <div class="detail-value">
                    {% if transaction.type == 'recharge' %}充值
                    {% elif transaction.type == 'reservation' %}预约扣费
                    {% elif transaction.type == 'consume' %}课程费用
                    {% elif transaction.type == 'refund' %}退款
                    {% elif transaction.type == 'penalty' %}违约金
                    {% elif transaction.type == 'freeze' %}余额冻结
                    {% elif transaction.type == 'unfreeze' %}余额解冻
                    {% else %}{{ transaction.type }}
                    {% endif %}
                </div>
            </div>

            <div class="detail-row">
                <div class="detail-label">
                    <i class="fas fa-money-bill-wave"></i>交易金额
                </div>
                <div class="detail-value {{ 'amount-positive' if transaction.amount > 0 else 'amount-negative' }}">
                    {% if transaction.amount > 0 %}+{% endif %}¥{{ "%.2f"|format(transaction.amount) }}
                </div>
            </div>

            <div class="detail-row">
                <div class="detail-label">
                    <i class="fas fa-clock"></i>交易时间
                </div>
                <div class="detail-value">{{ transaction.created_at.strftime('%Y年%m月%d日 %H:%M:%S') }}</div>
            </div>

            {% if transaction.payment_method %}
            <div class="detail-row">
                <div class="detail-label">
                    <i class="fas fa-credit-card"></i>支付方式
                </div>
                <div class="detail-value">
                    {% if transaction.payment_method == 'alipay' %}
                        <i class="fab fa-alipay me-2" style="color: #1677ff;"></i>支付宝
                    {% elif transaction.payment_method == 'wechat' %}
                        <i class="fab fa-weixin me-2" style="color: #07c160;"></i>微信支付
                    {% elif transaction.payment_method == 'unionpay' %}
                        <i class="fas fa-credit-card me-2" style="color: #e21f2f;"></i>银联支付
                    {% else %}
                        {{ transaction.payment_method }}
                    {% endif %}
                </div>
            </div>
            {% endif %}

            {% if transaction.payment_reference %}
            <div class="detail-row">
                <div class="detail-label">
                    <i class="fas fa-receipt"></i>支付凭证
                </div>
                <div class="detail-value highlight">{{ transaction.payment_reference }}</div>
            </div>
            {% endif %}

            {% if transaction.reference_type and transaction.reference_id %}
            <div class="detail-row">
                <div class="detail-label">
                    <i class="fas fa-link"></i>关联信息
                </div>
                <div class="detail-value">
                    {% if transaction.reference_type == 'reservation' %}
                        <a href="{{ url_for('student_reservations.detail', reservation_id=transaction.reference_id) }}"
                           class="text-decoration-none">
                            预约订单 #{{ transaction.reference_id }}
                        </a>
                    {% elif transaction.reference_type == 'refund' %}
                        原交易 #{{ transaction.reference_id }}
                    {% else %}
                        {{ transaction.reference_type }} #{{ transaction.reference_id }}
                    {% endif %}
                </div>
            </div>
            {% endif %}
        </div>

        <!-- 交易流程 -->
        <div class="detail-card">
            <h5 class="mb-4">
                <i class="fas fa-route me-2"></i>交易流程
            </h5>

            <div class="timeline">
                <div class="timeline-item">
                    <div class="timeline-content">
                        <div class="timeline-time">{{ transaction.created_at.strftime('%Y-%m-%d %H:%M:%S') }}</div>
                        <div class="fw-medium">交易发起</div>
                        <small class="text-muted">{{ transaction.description }}</small>
                    </div>
                </div>

                {% if transaction.status == 'completed' %}
                <div class="timeline-item">
                    <div class="timeline-content">
                        <div class="timeline-time">{{ transaction.created_at.strftime('%Y-%m-%d %H:%M:%S') }}</div>
                        <div class="fw-medium text-success">
                            <i class="fas fa-check-circle me-2"></i>交易完成
                        </div>
                        <small class="text-muted">交易已成功处理</small>
                    </div>
                </div>
                {% elif transaction.status == 'pending' %}
                <div class="timeline-item">
                    <div class="timeline-content">
                        <div class="timeline-time">处理中</div>
                        <div class="fw-medium text-warning">
                            <i class="fas fa-clock me-2"></i>等待处理
                        </div>
                        <small class="text-muted">交易正在处理中，请耐心等待</small>
                    </div>
                </div>
                {% elif transaction.status == 'failed' %}
                <div class="timeline-item">
                    <div class="timeline-content">
                        <div class="timeline-time">{{ transaction.created_at.strftime('%Y-%m-%d %H:%M:%S') }}</div>
                        <div class="fw-medium text-danger">
                            <i class="fas fa-times-circle me-2"></i>交易失败
                        </div>
                        <small class="text-muted">交易处理失败，如有疑问请联系客服</small>
                    </div>
                </div>
                {% endif %}
            </div>
        </div>

        <!-- 交易凭证 -->
        {% if transaction.status == 'completed' and transaction.payment_reference %}
        <div class="detail-card">
            <h5 class="mb-4">
                <i class="fas fa-qrcode me-2"></i>交易凭证
            </h5>

            <div class="qr-code-section">
                <p class="text-muted mb-3">扫描二维码查看交易凭证</p>
                <div class="qr-code">
                    <i class="fas fa-qrcode"></i>
                </div>
                <small class="text-muted">
                    凭证编号：{{ transaction.payment_reference }}<br>
                    请保存此凭证用于交易查询和售后服务
                </small>
            </div>
        </div>
        {% endif %}

        <!-- 操作按钮 -->
        <div class="action-buttons">
            <a href="{{ url_for('accounts.transactions') }}" class="btn btn-outline-secondary btn-action">
                <i class="fas fa-arrow-left me-2"></i>返回列表
            </a>

            {% if can_refund %}
            <button type="button" class="btn btn-warning btn-action" data-bs-toggle="modal" data-bs-target="#refundModal">
                <i class="fas fa-undo me-2"></i>申请退款
            </button>
            {% endif %}

            <button type="button" class="btn btn-info btn-action" onclick="printTransaction()">
                <i class="fas fa-print me-2"></i>打印凭证
            </button>

            <button type="button" class="btn btn-success btn-action" onclick="downloadReceipt()">
                <i class="fas fa-download me-2"></i>下载凭证
            </button>
        </div>

        <!-- 客服信息 -->
        <div class="detail-card text-center">
            <h6 class="text-muted mb-3">
                <i class="fas fa-headset me-2"></i>遇到问题？
            </h6>
            <p class="text-muted mb-3">如果您对此交易有任何疑问，请联系我们的客服团队</p>
            <div class="d-flex justify-content-center gap-3">
                <a href="tel:400-123-4567" class="btn btn-outline-primary">
                    <i class="fas fa-phone me-2"></i>400-123-4567
                </a>
                <a href="mailto:support@example.com" class="btn btn-outline-info">
                    <i class="fas fa-envelope me-2"></i>在线客服
                </a>
            </div>
        </div>
    </div>
</div>

<!-- 退款申请模态框 -->
{% if can_refund %}
<div class="modal fade" id="refundModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fas fa-undo me-2"></i>申请退款
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="refundForm">
                    <div class="mb-3">
                        <label class="form-label">退款原因</label>
                        <select class="form-select" name="refund_reason" required>
                            <option value="">请选择退款原因</option>
                            <option value="cancel_reservation">取消预约</option>
                            <option value="duplicate_payment">重复付款</option>
                            <option value="service_issue">服务问题</option>
                            <option value="system_error">系统错误</option>
                            <option value="other">其他原因</option>
                        </select>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">退款金额</label>
                        <div class="input-group">
                            <span class="input-group-text">¥</span>
                            <input type="number" class="form-control" name="refund_amount"
                                   value="{{ "%.2f"|format(transaction.amount|abs) }}"
                                   max="{{ "%.2f"|format(transaction.amount|abs) }}"
                                   min="0.01" step="0.01" required>
                        </div>
                        <small class="form-text text-muted">
                            最大可退款金额：¥{{ "%.2f"|format(transaction.amount|abs) }}
                        </small>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">详细说明</label>
                        <textarea class="form-control" name="description" rows="4"
                                  placeholder="请详细描述退款原因..." required></textarea>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">联系方式（可选）</label>
                        <input type="text" class="form-control" name="contact_method"
                               placeholder="请提供备用联系方式">
                    </div>

                    <div class="alert alert-warning">
                        <h6 class="alert-heading">退款说明</h6>
                        <ul class="mb-0">
                            <li>退款申请提交后，我们将在1-3个工作日内处理</li>
                            <li>退款将原路返回至您的支付账户</li>
                            <li>部分银行可能需要额外处理时间</li>
                            <li>如有疑问，请联系客服咨询</li>
                        </ul>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-warning" onclick="submitRefund()">
                    <i class="fas fa-paper-plane me-2"></i>提交申请
                </button>
            </div>
        </div>
    </div>
</div>
{% endif %}
{% endblock %}

{% block extra_js %}
<script>
$(document).ready(function() {
    // 页面加载动画
    $('.transaction-header').hide().fadeIn(800);
    $('.detail-card').each(function(index) {
        $(this).delay(index * 200).fadeIn(600);
    });

    // 生成二维码（如果有支付凭证）
    {% if transaction.payment_reference %}
    generateQRCode('{{ transaction.payment_reference }}');
    {% endif %}
});

// 生成二维码
function generateQRCode(data) {
    // 这里应该集成实际的二维码生成库，如 qrcode.js
    // 暂时显示占位符
    $('.qr-code').html('<i class="fas fa-qrcode"></i>');
}

// 打印交易凭证
function printTransaction() {
    window.print();
}

// 下载凭证
function downloadReceipt() {
    // 创建下载内容
    const content = `
交易凭证
================
交易编号：{{ transaction.id }}
交易类型：{{ transaction.description }}
交易金额：{{ "%.2f"|format(transaction.amount) }}元
交易时间：{{ transaction.created_at.strftime('%Y-%m-%d %H:%M:%S') }}
{% if transaction.payment_reference %}支付凭证：{{ transaction.payment_reference }}{% endif %}
交易状态：{{ transaction.status }}

本凭证由乒乓球培训管理系统生成
如有疑问请联系客服：400-123-4567
================
    `;

    // 创建下载链接
    const blob = new Blob([content], { type: 'text/plain' });
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = '交易凭证_{{ transaction.id }}.txt';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);

    showAlert('凭证下载成功', 'success');
}

// 提交退款申请
function submitRefund() {
    const form = document.getElementById('refundForm');
    const formData = new FormData(form);

    // 基本验证
    if (!formData.get('refund_reason')) {
        showAlert('请选择退款原因', 'warning');
        return;
    }

    if (!formData.get('description').trim()) {
        showAlert('请填写详细说明', 'warning');
        return;
    }

    const refundAmount = parseFloat(formData.get('refund_amount'));
    const maxAmount = {{ "%.2f"|format(transaction.amount|abs) }};

    if (refundAmount <= 0 || refundAmount > maxAmount) {
        showAlert('退款金额无效', 'warning');
        return;
    }

    // 提交退款申请
    $.ajax({
        url: '{{ url_for("accounts.api_apply_refund") }}',
        type: 'POST',
        data: {
            transaction_id: {{ transaction.id }},
            refund_reason: formData.get('refund_reason'),
            refund_amount: refundAmount,
            description: formData.get('description'),
            contact_method: formData.get('contact_method')
        },
        success: function(response) {
            if (response.success) {
                $('#refundModal').modal('hide');
                showAlert('退款申请已提交，我们将在1-3个工作日内处理', 'success');

                // 刷新页面显示最新状态
                setTimeout(function() {
                    location.reload();
                }, 2000);
            } else {
                showAlert('退款申请失败：' + response.error, 'danger');
            }
        },
        error: function(xhr, status, error) {
            console.error('退款申请失败:', error);
            showAlert('退款申请失败，请稍后重试', 'danger');
        }
    });
}

// 显示提示信息
function showAlert(message, type = 'info') {
    const alertHtml = `
        <div class="alert alert-${type} alert-dismissible fade show position-fixed"
             style="top: 20px; right: 20px; z-index: 9999;" role="alert">
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    `;

    $('body').append(alertHtml);

    // 3秒后自动隐藏
    setTimeout(function() {
        $('.alert').fadeOut();
    }, 3000);
}

// 复制交易编号
function copyTransactionId() {
    const transactionId = '{{ transaction.id }}';
    if (navigator.clipboard) {
        navigator.clipboard.writeText(transactionId).then(function() {
            showAlert('交易编号已复制到剪贴板', 'success');
        });
    } else {
        // 兼容旧浏览器
        const input = document.createElement('input');
        input.value = transactionId;
        document.body.appendChild(input);
        input.select();
        document.execCommand('copy');
        document.body.removeChild(input);
        showAlert('交易编号已复制到剪贴板', 'success');
    }
}

// 为交易编号添加点击复制功能
$(document).ready(function() {
    $('.detail-value.highlight').click(function() {
        copyTransactionId();
    }).css('cursor', 'pointer').attr('title', '点击复制交易编号');
});
</script>
{% endblock %}